package com.ftm.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.ftm.entity.AjaxResponse;
import com.ftm.entity.Goods;
import com.ftm.entity.GoodsType;
import com.ftm.service.GoodsManageService;
import com.ftm.service.GoodsTypeService;
import com.ftm.service.impl.GoodsManageServiceImpl;
import com.ftm.service.impl.GoodsTypeServiceImpl;
import com.ftm.tools.PageData;
import com.google.gson.Gson;

/**
 * Servlet implementation class GoodsServlet
 */
@WebServlet("/GoodsManageServlet")
@MultipartConfig
public class GoodsManageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// 接口引用 指向 实现类对象
	GoodsManageService gms = new GoodsManageServiceImpl();
	GoodsTypeService goodsTypeService = new GoodsTypeServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GoodsManageServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 标记当前为何种操作的变量
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		System.out.println("1.op:" + op);
		if ("".equals(op)) {
			System.out.println("46op" + op);
			// 分页查询
			doQueryByPage(request, response);
		} else if ("queryByPage".equals(op)) {
			// 分页查询
			doQueryByPage(request, response);
		} else if ("querylikes".equals(op)) {
			// 模糊搜索
			doQueryByPangeLikes(request, response);
		} else if ("del".equals(op)) {
			// 删除
			doAjaxDel(request, response);
		} else if ("upGoods".equals(op)) {
			// 修改
			doUpGoods(request, response);
		} else if ("doType".equals(op)) {
			// 分类选项
			doAjaxType(response);
		} else if ("addgoods".equals(op)) {
			// 添加功能
			doAddGoods(request, response);
		}
	}

	private void doAddGoods(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		System.out.println("add");
		response.setContentType("application/json;charset=utf-8");

		int shopid = 0;
		if (request.getParameter("shopid") != null) {
			shopid = Integer.parseInt(request.getParameter("shopid"));
		}

		// 获取属性
		String goodsname = request.getParameter("goodsname");
		double goodsprice = Double.parseDouble(request.getParameter("goodsprice"));
		String goodsinfo = request.getParameter("goodsinfo");
		int goodscount = Integer.parseInt(request.getParameter("goodscount"));
		
		Part file = request.getPart("cover-file");
		// 调用方法实现上传
		// fileName 参数fileName上传的目标位置是哪里？
		// 3 包含完整的路径名+文件名
		String pathString = request.getRealPath("/upload/");
		
		pathString += file.getSubmittedFileName();
		String cover = pathString;
		System.out.println("pathString  :" + pathString);
		// 4 写入目标位置
		file.write(pathString);
		
		
		int typeid = Integer.parseInt(request.getParameter("typeid"));
		int goodsstate = Integer.parseInt(request.getParameter("goodsstate"));
		Goods goods = new Goods(goodsname, goodsprice, goodsinfo, goodscount, cover, typeid, shopid, goodsstate);
		// 2 调用 service的方法
		boolean flag = gms.addGoods(goods);

		if (flag) {
			// 转发到显示servelt上进行查询
			// request.getRequestDispatcher("NewsTypeServlet").forward(request, response);

			doQueryByPage(request, response);

		} else {
			// 转发到回到newstype增加的页面
			request.setAttribute("msg", "添加失败！请重添加。");
			request.getRequestDispatcher("product_add.jsp").forward(request, response);
		}
	}

	private void doAjaxType(HttpServletResponse response) throws IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");

		// 2 调用 service的方法
		List<GoodsType> list = goodsTypeService.selGoodsTypeAll();

		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(list);

		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);

		// 5.关闭
		outPrintWriter.close();
	}
	//修改
	private void doUpGoods(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		int goodsid = 0;
		if (request.getParameter("goodsid") != null) {
			goodsid = Integer.parseInt(request.getParameter("goodsid"));
		}
		int shopid = 0;
		if (request.getParameter("shopid") != null) {
			shopid = Integer.parseInt(request.getParameter("shopid"));
		}
		// 获取属性
		String goodsname = request.getParameter("goodsname");
		double goodsprice = Double.parseDouble(request.getParameter("goodsprice"));
		String goodsinfo = request.getParameter("goodsinfo");
		int goodscount = Integer.parseInt(request.getParameter("goodscount"));
		
		
		String cover =null;
		if (request.getParameter("cover-file") != null) {
			Part file = request.getPart("cover-file");
			// 调用方法实现上传
			// fileName 参数fileName上传的目标位置是哪里？
			// 3 包含完整的路径名+文件名
			String pathString = request.getRealPath("/upload/");
			
			pathString += file.getSubmittedFileName();
			System.out.println("pathString  :" + pathString);
			// 4 写入目标位置
			file.write(pathString);
			cover = pathString;
		}else {
			cover = request.getParameter("cover");
		}
		int typeid = Integer.parseInt(request.getParameter("typeid"));
		int goodsstate = Integer.parseInt(request.getParameter("goodsstate"));

		// 2 调用 service的方法
		boolean flag = gms.upGoods(goodsname, goodsprice, goodsinfo, goodscount, cover, typeid, shopid, goodsstate,
				goodsid);

		if (flag) {
			// 转发到显示servelt上进行查询

			doQueryByPage(request, response);

		} else {
			
			request.setAttribute("msg", "修改失败！请重新修改。");
			request.getRequestDispatcher("product_list.jsp").forward(request, response);
		}
	}

	private void doAjaxDel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json;charset=utf-8");
		int goodsid = 0;
		if (request.getParameter("goodsid") != null) {
			goodsid = Integer.parseInt(request.getParameter("goodsid"));
		}

		// 2 调用 service的方法
		boolean flag = gms.delGoods(goodsid);

		AjaxResponse res = new AjaxResponse(flag + "", 200);
		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(res);

		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);

		// 5.关闭
		outPrintWriter.close();
	}

	// 模糊搜索
	private void doQueryByPangeLikes(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取请求参数
		String keywords = request.getParameter("keywords");
		System.out.println("1.keywords:" + keywords);
		int shopid = Integer.parseInt(request.getParameter("shopid"));
		System.out.println(shopid);

		// 每页起始位置
		int page = 1;
		// 每页记录数默认为10
		int pageSize = 10;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}

		// 3 调用 Service的方法
		PageData<Goods> goodsP = gms.queryGoodsShopLike(page, pageSize, shopid, keywords);
		request.setAttribute("goodsP", goodsP);
		// 4.-1转发回来的时候，我们将查询关键字也存储在request范围内
		request.setAttribute("shopid", shopid);
		// 5 转发
		request.getRequestDispatcher("product_list.jsp").forward(request, response);
	}

	// 分页查询
	private void doQueryByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		int shopid = 0;
		// 2获取请求参数
		if (request.getParameter("shopid") != null) {
			shopid = Integer.parseInt(request.getParameter("shopid"));
		}
		System.out.println(shopid);
		// 页码默认值为1
		int page = 1;
		// 每页记录数默认为10
		int pageSize = 10;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}

		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		// 3 调用 Service的方法
		PageData<Goods> goodsP = gms.queryGoodsShopid(page, pageSize, shopid);
		// 控制台输出(检测)
		System.out.println("62-goodsP:" + goodsP.getData());
		// 4传递PageData对象给jsp，此时传递的是pageData的对象
		request.setAttribute("goodsP", goodsP);
		// 4.-1转发回来的时候，我们将查询关键字也存储在request范围内
		request.setAttribute("shopid", shopid);
		// 5 转发
		request.getRequestDispatcher("product_list.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
	
		doGet(request, response);
	}

}
